﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing; 
using System.Drawing.Drawing2D; 
using App.Data;
using App.Core.Extensions;


public partial class Pages_Private_ProjectFileAttachment : BasePage
{
    private int _ProjectID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropdownList.BindProjectFileTypes(ddlFileType);
            BindEnquiryDetails();
        }
    }
    protected void BindPageInfo()
    {
        Page.Title = WebUtil.GetPageTitle("Upload File for Project");
        _ProjectID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
    }
    protected void BindEnquiryDetails()
    {
        if (_ProjectID > 0)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            Project project = context.Projects.SingleOrDefault(P => P.ID == _ProjectID);
            if (project == null)
            {
                WebUtil.ShowMessageBox(divMessage, "Sorry! requested project was not found.", true);
                pnlUploadContainer.Visible = false;
            }
            else
                ltrHeading.Text = String.Format("Add Picture, Brochure to Project: {0}", project.Name);
        }
        else
            ltrHeading.Text = "Add Picture, Brochure to Project.";
    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            String fileName = UploadAndSaveFile();
            SaveInSession(fileName);
        }
    }
    protected void SaveInSession(String fileName)
    {
        if (String.IsNullOrEmpty(fileName))
            hdnFileName.Value = String.Empty;
        else
        {
            ProjectFile file = new ProjectFile();
            //EnquiryFile attachment = new EnquiryFile();
            //file.ProjectID = _ProjectID;            
            file.FileTypeID = ddlFileType.SelectedValue.ToInt();
            file.FileName = fileName;
            if (file.FileTypeID != ConfigReader.ProjectBrocheureFileTypeID)
            {
                String [] parts = fileName.Split('|');
                file.FileName = parts[0];
                file.ThumbFileName = parts[1];
            }
            file.Created = DateTime.Now;
            file.Modified = DateTime.Now;
            file.ModifiedBy = SessionCache.CurrentUser.ID;
            IList<ProjectFile> files = SessionCache.CurrentProjectFiles;
            if (files.FirstOrDefault(F => F.FileName == fileName) == null)
                files.Add(file);
            SessionCache.CurrentProjectFiles = files;
            hdnFileName.Value = file.FileName;
        }
    }
    protected String UploadAndSaveFile()
    {
        if (fileEnquiry.HasFile)
        {
            String uploadDirectory = Path.Combine(Server.MapPath(AppConstants.TEMP_DIRECTORY), SessionCache.CurrentUser.ID.ToString());
            if (ddlFileType.SelectedValue.ToInt() == ConfigReader.ProjectBrocheureFileTypeID)
            {
                if (IsValidDocument(fileEnquiry.PostedFile))                
                    return saveFile(uploadDirectory);               
                else
                    WebUtil.ShowMessageBox(divAttachmentError, String.Format("Only Microsoft Word (*.doc, *.docx) and PDF (*.pdf) documents are allowed for {0}.", ddlFileType.SelectedItem.Text), true);
            }
            else
            {
                if (WebUtil.IsValidImageFile(fileEnquiry.PostedFile))
                {
                    String newImagePath = saveFile(uploadDirectory);
                    String thumbNailPath = GenerateThumbnail(Path.Combine(uploadDirectory, newImagePath));
                    return String.Format("{0}|{1}", newImagePath, Path.GetFileName(thumbNailPath));
                }
                else
                    WebUtil.ShowMessageBox(divAttachmentError, String.Format("Only Valid Image files (*.jpg, *.jpeg, *.gif, *.png) are allowed for {0}.", ddlFileType.SelectedItem.Text), true);

            }
        }
        return String.Empty;
    }
    private String saveFile(String uploadDirectory)
    {
        if (!Directory.Exists(uploadDirectory))
            Directory.CreateDirectory(uploadDirectory);
        //String fileName = String.Format("{0}_{1}", SessionCache.CurrentUser.ID, Path.GetFileName(fileEnquiry.FileName));
        String fileName = Path.GetFileName(fileEnquiry.FileName);
        fileEnquiry.SaveAs(Path.Combine(uploadDirectory, fileName));
        return fileName;
    }
    /// <summary>
    /// Checks Whethear the Uploaded file Is a Valid Document
    /// </summary>
    /// <param name="httpPostedFile"></param>
    /// <returns></returns>
    private bool IsValidDocument(HttpPostedFile httpPostedFile)
    {
        String extension = Path.GetExtension(httpPostedFile.FileName);
        if (String.Compare(extension, ".doc", true) == 0)
            return true;
        else if (String.Compare(extension, ".docx", true) == 0)
            return true;
        else if (String.Compare(extension, ".pdf", true) == 0)
            return true;
        return false;
    }
    public String GenerateThumbnail(String filePath)
    {
        String src = filePath; //"c:/myImages/a.jpg"; //absolute location of source image
        //String dest = "c:/myImages/a_th.jpg"; //absolute location of the new image created(thumbnail) 
        String dest = String.Format("{0}_Thumb{1}", Path.GetFileNameWithoutExtension(filePath), Path.GetExtension(filePath));
        dest = Path.Combine(Path.GetDirectoryName(filePath), dest);
        int thumbWidth = 132; //width of the image (thumbnail) to produce 
        //The code snippest shown here is in ASP .NET C#. You have to use these namespaces 
        //Following are the Steps along with example code: 
        //- Get the source image to a System.Drawing.Image object
        System.Drawing.Image image = System.Drawing.Image.FromFile(src);
        ///- Create a System.Drawing.Bitmap with the desired width and height of the thumbnail. 
        int srcWidth = image.Width;
        int srcHeight = image.Height;
        int thumbHeight = thumbWidth;//(srcHeight / srcWidth) * thumbWidth;
        Bitmap bmp = new Bitmap(thumbWidth, thumbHeight);

        //- Create a System.Drawing.Graphics object from the Bitmap which we will use to draw the high quality scaled image 
        System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
        //- Set the System.Drawing.Graphics object property SmoothingMode to HighQuality 
        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //- Set the System.Drawing.Graphics object property CompositingQuality to HighQuality
        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

        //- Set the System.Drawing.Graphics object property InterpolationMode to High
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //- Draw the original image into the target Graphics object scaling to the desired width and height
        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
        gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);

        //- Save to destination file
        bmp.Save(dest);
        bmp.Dispose();
        image.Dispose(); 
        return dest;
    }
}